package edu.jkd.filter;

import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
        //1、获取本次请求的URL
        String requestURL=  request.getRequestURI(); //backend/index.html
        //定义不需要处理的请求路径，直接放行

        String [] urls=new String[]{
                "/demo/login",
                "/demo/images/*",
                "/demo/bootstrap-3.4.1-dist/*",
                "/demo/css/*",
                "/demo/js/*",
                "/demo/layui/*",
                "/demo/customer/*",
                "/demo/sign_in.jsp",
        };
        if(request.getSession().getAttribute("user")!=null){
            filterChain.doFilter(request,response);
            return;
        }
        boolean check = check(urls, requestURL);
        if(check){
            System.out.println("放行");
            filterChain.doFilter(request,response);
            return;
        }
        request.getRequestDispatcher("/login.jsp").forward(request,response);

    }
    public boolean check (String [] urls,String requestURL){
        for (String url:urls
        ) {
            boolean match= PATH_MATCHER.match(url,requestURL);
            if(match){
                return true;
            }
        }
        return false;
    }
}
